package com.magnate.software.shiro.crypto.impl;

import com.magnate.software.common.utils.PropertyConfigurerUtils;
import com.magnate.software.shiro.crypto.PasswordEncryptService;
import com.magnate.software.shiro.domain.enums.PropertiesConstants;
import com.magnate.software.shiro.domain.po.Account;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

/**
 * 密码加密工具
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2016/1/12 10:39
 */
@Service("passwordEncryptService")
public class PasswordEncryptServiceImpl implements PasswordEncryptService {

    private static final String salt = PropertyConfigurerUtils.getProperty(PropertiesConstants.PASSWORD_SALT.getCode());

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private String algorithmName = "md5";
    private int hashIterations = 2;

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    @Override
    public void encryptPassword(Account account) {
        //account.setSalt(randomNumberGenerator.nextBytes().toHex());
        String newPassword = new SimpleHash(
                algorithmName,
                account.getPassword(),
                ByteSource.Util.bytes(account.getAccount() + salt), // 账户+盐
                hashIterations).toHex();
        account.setPassword(newPassword);
    }

}
